package com.yuexunit.mobilenurse.module.DocAdvice.model.impl;

import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.DocAdvice.model.IInjectionModel;
import com.yuexunit.mobilenurse.util.CreateJson;

import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;

/**
 * Created by work-jx on 2016/2/3.
 */
public class InjectionModel implements IInjectionModel{
    //记录Log
    private final Logger log = LoggerFactory.getLogger(DispensingModel.class);

    @Override
    public Observable getInjectionListData(final String visitno) {
        return Observable.create(new Observable.OnSubscribe<Object>() {

            @Override
            public void call(Subscriber<? super Object> subscriber) {
                String result = null;

                String nameSpace = AppConfig.WEB_NAME_SPACE;
                String methodName = AppConfig.WEB_NAME_METHOD;
                String url = AppConfig.WEB_CONTENT;

                SoapObject request = new SoapObject(nameSpace, methodName);
                request.addProperty("XmlString", CreateJson.Orderlist_Json(visitno));//住院号
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                envelope.bodyOut = request;
                envelope.dotNet = true;
                HttpTransportSE ht = new HttpTransportSE(url, AppConfig.TIMEOUT);
                Object response = null;
                try {
                    ht.call(nameSpace + methodName, envelope);
                    response = envelope.getResponse();
                    //记录传输到服务器及传回的数据
                    log.debug(CreateJson.LOG_JSON(url + ",mhs_order_list", "2", visitno, response.toString()));
                    if (response != null) {
                        JSONObject all, body;
                        try {
                            all = new JSONObject(response.toString());
                            body = all.getJSONObject("body");
                            result = body.getString("response");
                        } catch (JSONException e) {
                            log.error("JSONException:", e);
                            subscriber.onError(e);
                        }
                        if ("null".equals(result)) {
                            subscriber.onError(new Exception());
                        }
                    } else {
                        subscriber.onError(new Exception());
                    }

                } catch (Exception e) {
                    log.error("Exception", e);
                    e.printStackTrace();
                    subscriber.onError(e);
                }
                subscriber.onNext(response);
            }
        }).map(new Func1<Object, String>() {
            @Override
            public String call(Object response) {
                return (String) response.toString();
            }
        });
    }

    @Override
    public Observable ExecOrder(final String visitno, final String barcode, final String nurseid) {
        return Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                String nameSpace = AppConfig.WEB_NAME_SPACE;
                String methodName = AppConfig.WEB_NAME_METHOD;
                String url = AppConfig.WEB_CONTENT;
                SoapObject request = new SoapObject(nameSpace, methodName);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",java.util.Locale.getDefault());
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                String str = formatter.format(curDate);
                request.addProperty("XmlString", CreateJson.Orderexec_Json3(visitno, barcode,
                        Integer.valueOf(nurseid), str, AppConfig.EXECTYPE));

                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                envelope.bodyOut = request;
                envelope.dotNet = true; //very important for compatibility
                HttpTransportSE ht = new HttpTransportSE(url, AppConfig.TIMEOUT);
                Object response = null;
                try {
                    ht.call(nameSpace + methodName, envelope);
                    response = envelope.getResponse();
                    //记录传输到服务器及传回的数据
                    log.debug(CreateJson.LOG_JSON(url + ",mhs_order_exec", "2", CreateJson.Orderexec_Json(visitno
                            , barcode, Integer.valueOf(nurseid), formatter.format(curDate), AppConfig.EXECTYPE), response.toString()));
                    if (response == null) {
                        subscriber.onError(new Exception());
                    }
                } catch (Exception e) {
                    log.error("Exception:" + e);
                    e.printStackTrace();
                    subscriber.onError(e);
                }
                subscriber.onNext(response);
                subscriber.onCompleted();
            }
        }).map(new Func1<Object, String>() {
            @Override
            public String call(Object response) {
                return (String) response.toString();
            }
        });
    }
}
